package cn.xutongxue.book_sales.controller;


import cn.xutongxue.book_sales.base.Result;
import cn.xutongxue.book_sales.entity.Address;
import cn.xutongxue.book_sales.entity.Goods;
import cn.xutongxue.book_sales.entity.Order;
import cn.xutongxue.book_sales.entity.User;
import cn.xutongxue.book_sales.service.AddressService;
import cn.xutongxue.book_sales.service.GoodsService;
import cn.xutongxue.book_sales.service.OrderService;
import cn.xutongxue.book_sales.service.UserService;
import cn.xutongxue.book_sales.service.impl.OrderServiceImpl;
import cn.xutongxue.book_sales.untils.OrderUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author XuTongXue
 * @since 2021-12-02
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private OrderUtils orderUtils;

    @Resource
    private UserService userService;

    @Resource
    private AddressService addressService;

    @Resource
    private GoodsService goodsService;

    @PostMapping("/create")
    public Result create(@RequestBody Order order) {

        User user = userService.getById(order.getOrderUserId());

        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        Integer addressUserId = order.getOrderUserId();

        wrapper.eq("address_user_id",addressUserId);
        Address address = addressService.getOne(wrapper);
        System.out.println(address);

        order.setOrderNumber(orderUtils.getOrderNumber());

        order.setOrderName(user.getName());
        order.setOrderPhone(address.getAddressUserPhone());
        order.setOrderAddress(address.getAddressDetailed());
        order.setOrderState(0);

        if(orderService.save(order)) {
            return Result.ok("购买成功",null);
        }
        return Result.fail(1301, "购买失败");
    }

    @GetMapping("/get")
    public Result getAll(@RequestParam("order_user_id") Integer orderUserId) {

        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper
                .eq("order_user_id",1);
        System.out.println(orderUserId);
        List<Order> list = orderService.list(wrapper);

        return Result.ok(list);
    }

    @GetMapping("/getall")
    public Result getAllOrder() {
        List<Order> list = orderService.list();
        return Result.ok(list);
    }

    @PostMapping("/delete")
    public Result deleteOrder(@RequestBody Order order) {
        if(orderService.removeById(order.getOrderId())) {
            return Result.ok(null);
        }
        return Result.fail(1302, "删除失败");
    }

}
